package com.changgou.com.changgou.pay.controller;


import com.alibaba.fastjson.JSON;
import com.changgou.com.changgou.pay.service.WxPayService;
import com.changgou.entity.Result;
import com.changgou.entity.StatusCode;
import com.changgou.util.ConvertUtils;
import com.github.wxpay.sdk.WXPayUtil;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/wxpay")
public class WxPayController {
    @Autowired
    private WxPayService wxPayService;

    @Autowired
    private RabbitTemplate rabbitTemplate;
    /**
     * 下单
     * @param orderId
     * @param money
     * @return
     */
    @GetMapping("/nativePay")
    public Result nativePay(@RequestParam("orderId")String orderId,@RequestParam("money")Integer money){
        Map map=wxPayService.nativePay(orderId,money);
        return new Result( true, StatusCode.OK,"",map );
    }
    /**
     * 回调
     */
    @RequestMapping("/notify")
    public void notifyLogic(HttpServletRequest request, HttpServletResponse response){
        System.out.println("支付成功回调。。。。");
        try {
            //输入流转换为xml字符串
            // 我们可以将此xml字符串，转换为map，提取其中的out_trade_no（订单号），根据订单号修改订单状态。
            String xml = ConvertUtils.convertToString(request.getInputStream());
            //解析
            Map<String, String> map = WXPayUtil.xmlToMap(xml);
            //查询订单
            if ("SUCCESS".equals(map.get("result_code"))){
                //如果返回状态码为成功
                //通过获取订单id 查询微信中的订单信息
                Map queryOrder = wxPayService.queryOrder(map.get("out_trade_no"));
                System.out.println("查询订单返回结果："+queryOrder);
                //如果查询结果是成功发送到mq
                if("SUCCESS".equals(queryOrder.get("result_code"))){
                    Map m=new HashMap();
                    //订单id
                    m.put("orderId",queryOrder.get("out_trade_no"));
                    //事务id
                    m.put( "transactionId",queryOrder.get( "transaction_id" ));

                    rabbitTemplate.convertAndSend("","order_pay", JSON.toJSONString(m));
                    //发送订单id给交换机 用于前端页面跳转
                    rabbitTemplate.convertAndSend("paynotify","",map.get("out_trade_no"));
                }

            }

            System.out.println(xml);
            //给微信支付一个成功的响应。
            response.setContentType("text/xml");
            String data = "<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>";
            response.getWriter().write(data);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    /**
     * 关闭微信订单
     * @param orderId
     * @return
     */
    @PutMapping("/close/{orderId}")
    public Result closeOrder(@PathVariable String orderId){
       Map map= wxPayService.closeOrder(orderId);
       return new Result(true,StatusCode.OK,"",map);
    }
    /**
     * 查询微信订单
     * @param orderId
     * @return
     */
    @GetMapping("/query/{orderId}")
    public Result queryOrder(@PathVariable String orderId){
        Map map = wxPayService.queryOrder(orderId);
        return new Result(true,StatusCode.OK,"",map);
    }
}
